<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <!--            <a-row>
                          <a-col :span="3">

                          </a-col>
                          <a-col :span="18">
                            <span class="cu-font">基础信息</span>
                            <a-divider style="margin: 16px 0" />
                          </a-col>
                        </a-row>-->
            <span class="cu-font">基础信息</span>
            <a-divider style="margin: 16px 0" />
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入合同名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="isShow">
            <a-form-model-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number">
              <a-input v-model="model.number" placeholder="请输入编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">

              <JSelectMultiUser v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl"
                                @change="kehuChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactsIds">
              <lianxiren v-model="model.contactsIds" :query-config="lianxirenConfig" :multiple="false"
                         :url="lianxirenUrl" v-if="customerIdShow" @change="jihuiChange"></lianxiren>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联机会" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="opportunityId">

              <xiaoshoujihui displayKey="number" v-model="model.opportunityId" :query-config="jihuiConfig"
                             :multiple="false" :url="xiaoshoujihuiUrl" v-if="customerIdShow"></xiaoshoujihui>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联报价单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="quotationId">
              <baojiadan displayKey="number" v-model="model.quotationId" :query-config="baojiadanConfig"
                         :multiple="false" :url="baojiadanUrl" v-if="customerIdShow"></baojiadan>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="签订人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signedBy">
              <j-select-user-by-dep placeholder="请输入签订人" v-model="model.signedBy" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="签订时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signedTime">
              <j-date placeholder="请选择签订时间" v-model="model.signedTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="到期时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endTime">
              <j-date placeholder="请选择到期时间" v-model="model.endTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="合同状态" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="state">
              <j-dict-select-tag type="list" v-model="model.state" dictCode="contract_order_state"
                                 placeholder="请选择合同状态" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">
              <j-select-user-by-dep v-model="model.directorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds">
              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <span class="cu-font">销售信息</span>
            <a-divider style="margin: 16px 0" />
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="产品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productList">
              <a-button class="editable-add-btn" @click="chanPinAdd" :disabled="priceDisable">
                添加产品
              </a-button>
              <a-table bordered
                       :dataSource="dataSource"
                       :columns="columns"
                       :pagination="false"
                       :scroll="{x:true}"
                       rowKey="id">

                <template slot="name" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="number" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                规格-->
                <template slot="specifications" slot-scope="text, record,index">
                  <span>{{ text }}</span>
                </template>
                <!--                条码-->
                <template slot="barCode" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                报价单位-->
                <template slot="unit" slot-scope="text, record">
                  <j-dict-select-tag type="list" v-model="text" dictCode="product_unit" disabled />
                </template>
                <!--                数量-->
                <template slot="num" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                单价-->
                <template slot="unitPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                折扣-->
                <template slot="discount" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                售价-->
                <template slot="quotedPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                报价小计-->
                <template slot="quotedPriceTotal" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                备注-->
                <template slot="remarks" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="operation" slot-scope="text, record,index" v-if="!priceDisable">
                  <a @click="contactsEdit(record)">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="contactsDel(index)">删除</a>

                </template>
              </a-table>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="产品合计" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalProducts">
              <a-input-number :defaultValue="0" v-model="model.totalProducts" placeholder="请输入产品合计"
                              style="width: 100%" :disabled="priceDisable" />
            </a-form-model-item>
          </a-col>
          <a-col :span=" 24
              ">
            <a-form-model-item label="整体折扣率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="discountRate">
              <a-input-number v-model="model.discountRate" placeholder="请输入折扣率" style="width: 100%"
                              @blur="quotationAmountComputer" :disabled="priceDisable"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span=" 24
                ">
            <a-form-model-item label="其他费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherExpenses">
              <a-input-number v-model="model.otherExpenses" placeholder="请输入其他费用" style="width: 100%"
                              @blur="quotationAmountComputer" :disabled="priceDisable" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="优惠金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="preferentialAmount">
              <a-input-number v-model="model.preferentialAmount" placeholder="请输入优惠价钱" style="width: 100%"
                              @blur="quotationAmountComputer" :disabled="priceDisable" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="合同金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
              <a-input-number v-model="model.contractAmount" placeholder="请输入合同价钱" style="width: 100%"
                              :disabled="priceDisable" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
             <span class="cu-font">关联回款</span>
             <a-divider style="margin: 16px 0" />
           </a-col>
           <a-col :span="24">
             <a-form-model-item label="回款单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentReceiptId">
               <div>
                 <a-button type="primary" @click="openHuikuandan" :disabled="huikuandanShow">回款单</a-button>
                 {{ `(用于记录新回款。 可添加金额: ${canBeAdd})` }}
               </div>
               <div>
                 <a-table
                   v-if="huikuandanTableShow"
                   ref="huikuandantable"
                   size="middle"
                   :scroll="{x:true}"
                   rowKey="id"
                   bordered
                   :columns="huikuandanColumns"
                   :pagination="false"
                   :dataSource="huikuandanTable">
                   <template slot="collectionAccount" slot-scope="text,record">
                     <j-dict-select-tag type="list" v-model="record.collectionAccount"
                                        disabled dictCode="collection_account" />
                   </template>
                   <span slot="operation" slot-scope="text, record,index">
                     <a @click="huikuandanTableEdit(record)">编辑</a>
                     <a-divider type="vertical" />
                     <a @click="huikuandanTableDel(index)">删除</a>
                   </span>
                 </a-table>
               </div>
             </a-form-model-item>
           </a-col>
           <a-col :span="24">
             <a-form-model-item label="应收款" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivablesIds">
               <div>
                 <a-button type="primary" @click="openYingshoukuan" :disabled="huikuandanShow">应收款</a-button>
                 {{ `(用于对未回款金额制定计划催收。 可添加金额:  ${canBeAdd})` }}
               </div>
               <div>
                 <a-table
                   v-if="yingshoukuanTableShow"
                   ref="yingshoukuantable"
                   size="middle"
                   :scroll="{x:true}"
                   rowKey="id"
                   bordered
                   :columns="yingshoukuanColumns"
                   :pagination="false"
                   :dataSource="yingshoukuanTable">
                   <template slot="state" slot-scope="text,record">
                     <j-dict-select-tag type="list" v-model="record.state"
                                        disabled dictCode="receivables_state" />
                   </template>
                   <template slot="type" slot-scope="text,record">
                     <j-dict-select-tag type="list" v-model="record.type"
                                        disabled dictCode="receivables_type" />
                   </template>
                   <span slot="operation" slot-scope="text, record,index">
                     <a @click="yingshoukuanTableEdit(record)">编辑</a>
                     <a-divider type="vertical" />
                     <a @click="yingshoukuanTableDel(index)">删除</a>
                   </span>>
                 </a-table>
               </div>
             </a-form-model-item>
           </a-col>-->
          <a-col :span="24">
            <span class="cu-font">扩展信息</span>
            <a-divider style="margin: 16px 0" />
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="contractType">
              <j-dict-select-tag type="list" v-model="model.contractType" dictCode="contract_order_type"
                                 placeholder="请选择合同类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="payType">
              <j-dict-select-tag type="list" v-model="model.payType" dictCode="contract_pay_type"
                                 placeholder="请选择付款方式" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="发货状态" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="deliverType">
              <j-dict-select-tag type="list" v-model="model.deliverType" dictCode="contract_deliver_state"
                                 placeholder="请选择发货状态" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="物流公司" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="logisticsCompany">
              <j-dict-select-tag type="list" v-model="model.logisticsCompany" dictCode="contract_logistics_company"
                                 placeholder="请选择物流公司" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="物流编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="logisticsNumber">
              <a-input v-model="model.logisticsNumber" placeholder="请输入物流编号"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <huikuandanModel ref="huikuandanModel" @ok="huikuandanOK"></huikuandanModel>
    <yingshoukuanModal ref="yingshoukuanModel" @ok="yingshoukuanOK"></yingshoukuanModal>
    <productInfoModal ref="productInfo" @ok="productEditOK"></productInfoModal>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUserCustom'
import lianxiren from '@/components/jeecgbiz/lianxirenCustom'
import xiaoshoujihui from '@/components/jeecgbiz/xiaoshoujihui/index'
import baojiadan from '@/components/jeecgbiz/baojiadan/index'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
import EditableCell from '@/components/EditableCell/cell'
import huikuandanModel from './PaymentCollectionModal'
import yingshoukuanModal from './ReceivablesModal'
import productInfoModal from '@comp/ProductInfo/ProductInfoModal'

export default {
  name: 'ContractOrderForm',
  components: {
    JSelectMultiUser,
    lianxiren,
    xiaoshoujihui,
    JSelectUserByDep,
    baojiadan,
    EditableCell,
    huikuandanModel,
    yingshoukuanModal,
    productInfoModal
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      priceDisable: false,
      //应收款表格显隐
      yingshoukuanTableShow: false,
      yingshoukuanTable: [],
      //应收款计数器
      yingshoukuanCount: 1,
      //回款单计数器
      huikuandanCount: 1,
      //回款单表格显隐
      huikuandanTableShow: false,
      //可添加金额
      canBeAdd: 0,
      //回款单表格
      huikuandanTable: [],
      huikuandanShow: true,
      kehuurl: '/customer/customer/lists?filed=2&id=',
      // 选择用户查询条件配置
      selectUserQueryConfig: [
        { key: 'phone', label: '电话' }
      ],
      isShow: false,
      //联系人
      customerIdShow: false,
      // lianxirenUrl: '/sys/common/queryCustomerId?customerId=',
      lianxirenUrl: '/contacts/contacts/list?customerId=',
      lianxirenConfig: [
        { key: 'name', label: '姓名' }
        /* {key: 'leixing', label: '类型'},
        {key: 'tel', label: '电话'} */

      ],
      //销售机会
      // xiaoshoujihuiUrl: '/sys/common/querySalesOpportuninty?customerId=',
      xiaoshoujihuiUrl: '/sales/salesOpportuninty/list?customerId=',
      jihuiConfig: [
        { key: 'number', label: '编号' }

      ],
      //报价单
      // baojiadanUrl: '/sys/common/queryQuotation?customerId=',
      baojiadanUrl: '/quotation/quotation/list?customerId=',
      baojiadanConfig: [
        { key: 'number', label: '编号' }

      ],
      tableShow: true,
      //产品使用
      count: 1,
      dataSource: [],
      columns: [
        {
          title: '产品名称',
          dataIndex: 'name',
          key: 'name',
          width: 200,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '产品编号',
          dataIndex: 'number',
          width: 200,
          key: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '规格',
          dataIndex: 'specifications',
          width: 150,
          key: 'specifications',
          scopedSlots: { customRender: 'specifications' }
        },
        {
          title: '产品条码',
          dataIndex: 'barCode',
          width: 150,
          key: 'barCode',
          scopedSlots: { customRender: 'barCode' }
        },
        {
          title: '报价单位',
          dataIndex: 'unit',
          key: 'unit',
          width: 150,
          scopedSlots: { customRender: 'unit' }
        },
        /* {
          title: '分类',
          dataIndex: 'type',
          key: 'type',
          width: 150,
          scopedSlots: { customRender: 'type' }
        }, */
        {
          title: '数量',
          dataIndex: 'num',
          key: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          key: 'unitPrice',
          width: 150,
          scopedSlots: { customRender: 'unitPrice' }
        },
        {
          title: '折扣(%)',
          dataIndex: 'discount',
          key: 'discount',
          width: 150,
          scopedSlots: { customRender: 'discount' }
        },
        {
          title: '售价',
          dataIndex: 'quotedPrice',
          key: 'quotedPrice',
          width: 150,
          scopedSlots: { customRender: 'quotedPrice' }
        },
        {
          title: '报价小计',
          dataIndex: 'quotedPriceTotal',
          key: 'quotedPriceTotal',
          width: 150,
          scopedSlots: { customRender: 'quotedPriceTotal' }
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          key: 'remarks',
          width: 150,
          scopedSlots: { customRender: 'remarks' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 130,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      huikuandanColumns: [
        {
          title: '编号',
          dataIndex: 'number',
          width: '20%',
          key: 'number'
        },
        {
          title: '回款金额',
          dataIndex: 'collectionAmount',
          key: 'collectionAmount',
          width: '20%'
        },
        {
          title: '回款日期',
          dataIndex: 'collectionDate',
          key: 'collectionDate',
          width: '20%'
        },
        {
          title: '收款账户',
          dataIndex: 'collectionAccount',
          key: 'collectionAccount',
          width: '20%',
          scopedSlots: { customRender: 'collectionAccount' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: '20%',
          // fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      yingshoukuanColumns: [
        {
          title: '编号',
          dataIndex: 'number',
          width: '20%',
          key: 'number'
        },
        {
          title: '应收金额',
          dataIndex: 'amountReceivable',
          key: 'amountReceivable'
          // width: '20%'
        },
        {
          title: '回款状态',
          dataIndex: 'state',
          key: 'state',
          width: '20%',
          scopedSlots: { customRender: 'state' }
        },
        {
          title: '预计回款日期',
          dataIndex: 'estimatedCollectionDate',
          key: 'estimatedCollectionDate'
          // width: '20%'
        },
        {
          title: '回款类型',
          dataIndex: 'type',
          key: 'type',
          // width: '20%',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          key: 'remark'
          // width: '20%'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 100,
          // fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      model: {
        discountRate: 100,
        contractAmount: 0
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        name: [
          { required: true, message: '请输入合同名称!' }
        ],
        number: [
          { required: true, message: '请输入编号!' }
        ],
        customerId: [
          { required: true, message: '请输入客户ID!' }
        ],
        contactsIds: [
          { required: false, message: '请输入联系人IDS!' }
        ],
        opportunityId: [
          { required: false, message: '请输入机会ID!' }
        ],
        quotationId: [
          { required: false, message: '请输入报价ID!' }
        ],
        discountRate: [
          { required: true, message: '请输入整体折扣率!' },
          {
            validator: (rule, value, callback) => {

              if (Number(value) < 1 || Number(value) > 100) {
                callback(false)
              } else {
                callback()

              }
            },
            message: '整单折扣率请控制在1到100之间',
            trigger: ['blur']
          }
        ],
        signedBy: [
          { required: true, message: '请选择!' }
        ],
        state: [
          { required: true, message: '请选择!' }
        ],
        signedTime: [
          { required: true, message: '请输入签订时间!' }
        ],
        contractAmount: [
          { required: true, message: '请输入!' },
          { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ],
        directorIds: [
          { required: true, message: '请输入负责人IDS!' }
        ],
        collaboratorIds: [
          { required: false, message: '请输入协同人IDS!' }
        ],
        productIds: [
          { required: true, message: '请输入产品IDS!' }
        ],
        /* paymentReceiptId: [
          { required: true, message: '请输入回款单ID!' }
        ],
        receivablesIds: [
          { required: true, message: '请输入应收款IDS!' }
        ], */
        contractType: [
          { required: false, message: '请输入合同类型(1.直销合同 2.代理合同 3.服务合同 4.快销合同)!' }
        ],
        payType: [
          { required: false, message: '请输入付款方式(1.网银转账 2.现金 3.支票  4.电汇 5.承兑汇票)!' }
        ]
      },
      url: {
        add: '/contractorder/contractOrder/add',
        edit: '/contractorder/contractOrder/edit',
        queryById: '/contractorder/contractOrder/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  watch: {
    'model.customerId': {
      deep: true,
      handler(newValue, oldValue) {
        // console.log('model.customerID变化')

        if (!newValue || newValue !== oldValue) {
          this.customerIdShow = false
        }
        // console.log('newValue', newValue)
        // console.log('oldValue', oldValue)
        if (newValue) {
          this.$nextTick(() => {
            this.customerIdShow = true
            this.kehuurl = '/customer/customer/lists?filed=2&id=' + newValue
            console.log('执行新的kehuurl', this.kehuurl)
            if (this.model.customerId) {
              this.xiaoshoujihuiUrl = '/sales/salesOpportuninty/lists?customerId=' + newValue
              // + '&id=' + this.model.opportunityId
              this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + newValue + '&id=' + this.model.contactsIds
              // this.baojiadanUrl = '/sys/common/queryQuotation?customerId=' + newValue + '&id=' + this.model.quotationId
              /* 原始的 */
              /* this.baojiadanUrl = '/quotation/quotation/list?customerId=' + newValue + '&id=' + this.model.quotationId */
              this.baojiadanUrl = '/quotation/quotation/lists?customerId=' + newValue
            } else {
              this.xiaoshoujihuiUrl = '/sales/salesOpportuninty/lists?customerId=' + newValue
              this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + newValue
              // this.baojiadanUrl = '/sys/common/queryQuotation?customerId=' + newValue
              this.baojiadanUrl = '/quotation/quotation/lists?customerId=' + newValue
            }
          })

        }
      }
    },
    'model.contractAmount': {
      deep: true,
      immediate: true,
      handler(Nval, Oval) {
        //控制回款单+应收款显隐
        console.log('回款单显隐', Nval)
        // Nval > 0 ? this.huikuandanShow = false : this.huikuandanShow = true
        if (Nval > 0) {
          this.huikuandanShow = false
        } else {
          this.huikuandanShow = true
        }

        this.checkHuikuandanAll()
      }
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    //产品编辑
    contactsEdit(record) {
      this.$refs.productInfo.edit(record)
    },
    productEditOK(res) {
      console.log('添加产品返回数据', res)
      const { count, dataSource } = this
      if (res.key) {
        //编辑的情况
        const dataSource = [...this.dataSource]
        let target = dataSource.find((item) => item.key == res.key)
        target = Object.assign(target, res)
        this.dataSource = dataSource
      } else {
        //新增的情况
        let newData = Object.assign(res, { key: count })
        this.dataSource = [...this.dataSource, newData]
        this.count += 1
      }
      this.totalProductsComputer()

    },
    add() {
      this.edit(this.modelDefault)
      this.isShow = false
      this.model.totalProducts = 0  //默认产品合计
    },
    edit(record) {
      if (record.paymentReceiptIdList.length > 0 || record.receivablesIdsList.length > 0) {
        this.priceDisable = true
      }
      this.isShow = true
      this.model = Object.assign({}, record)
      let count = 0
      let huikuandancount = 0
      let yingshoukuancount = 0
      console.log('==============record', record)
      if (record.productList) {
        record.productList.map(res => {
          res.key = count += 1
          return res
        })
        console.log('编辑初始化产品列表', record.productList)
        this.dataSource = record.productList
      }
      //回款单
      // this.model.paymentReceiptId = this.huikuandanTable
      //应收款
      // this.model.receivablesIds = this.yingshoukuanTable

      if (record.paymentReceiptIdList) {
        record.paymentReceiptIdList.map(res => {
          res.key = huikuandancount += 1
          return res
        })
        this.huikuandanTable = record.paymentReceiptIdList
        this.huikuandanTableShow = true
      }
      if (record.receivablesIdsList) {
        record.receivablesIdsList.map(res => {
          res.key = yingshoukuancount += 1
          return res
        })
        this.yingshoukuanTable = record.receivablesIdsList
        this.yingshoukuanTableShow = true
      }
      this.visible = true
    },
    kehuChange(e) {
      console.log(e)
      this.customerIdShow = false
      this.model.opportunityId = ''
      this.model.contactsIds = ''
      /* this.xiaoshoujihuiUrl = '/sys/common/querySalesOpportuninty?customerId=' + e
      this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + e */
    },
    jihuiChange(e) {
      console.log(e)
    },
    //添加产品
    chanPinAdd() {
      this.$refs.productInfo.add()
    },
    jpopCallBack(e) {
      console.log('e', e)
    },
    truefalseChange() {
      this.tableShow = false
      this.$nextTick(() => {
        this.tableShow = true
      })
    },

    //总价计算
    totalProductsComputer() {
      const ageSum = this.dataSource.reduce((ageSum, e) => {
        return ageSum += Number(e.quotedPriceTotal)
      }, 0)
      this.model.totalProducts = ageSum
      this.quotationAmountComputer()
    },
    //报价金额变化
    quotationAmountComputer(item, Nval) {
      if (this.dataSource.length <= 0) {
        console.log('无产品')
        this.model.contractAmount = 0
        return false
      }
      console.log('总价金额变化quotationAmountComputer()')
      this.model.contractAmount = Number(this.model.totalProducts) * Number(this.model.discountRate) / 100 + (this.model.otherExpenses ? Number(this.model.otherExpenses) : 0) - (this.model.preferentialAmount ? Number(this.model.preferentialAmount) : 0)
    },
    //移除产品列表里的某一条产品
    contactsDel(index) {
      console.log(index)
      this.dataSource.splice(index, 1)
      this.model.productList = this.dataSource
      //重新计算总价
      this.totalProductsComputer()
      this.quotationAmountComputer('删除以重新计算总价', null)
    },
    submitForm() {

      const that = this
      this.model.productList = this.dataSource
      //回款单
      this.model.paymentReceiptIdList = this.huikuandanTable
      //应收款
      this.model.receivablesIdsList = this.yingshoukuanTable

      let obj = Object.assign({}, this.model)
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, obj, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    //回款单相关
    openHuikuandan() {
      this.$refs.huikuandanModel.add()
      this.$refs.huikuandanModel.passON(this.canBeAdd)
    },
    //回款单表格回传
    huikuandanOK(res) {
      console.log('添加回款单返回数据', res)
      const { huikuandanCount, huikuandanTable } = this
      if (res.key) {
        //编辑的情况
        const huikuandanTable = [...this.huikuandanTable]
        let target = huikuandanTable.find((item) => item.key == res.key)
        target = Object.assign(target, res)
        this.huikuandanTable = huikuandanTable
      } else {
        //新增的情况
        let newData = Object.assign(res, { key: huikuandanCount })
        this.huikuandanTable = [...this.huikuandanTable, newData]
        this.huikuandanCount += 1
      }

      //这里要区分是编辑还是新增的回传
      this.huikuandanTable.length > 0 ? this.huikuandanTableShow = true : this.huikuandanTableShow = false
      this.checkHuikuandanAll()
      console.log('回款单表格实时动态', this.huikuandanTable)
    },
    //回款单表格编辑
    huikuandanTableEdit(record) {
      console.log('record', record)
      this.$refs.huikuandanModel.edit(record)
      this.$refs.huikuandanModel.passONEdit(this.canBeAdd + Number(record.collectionAmount))
    },
    //回款单表格删除
    huikuandanTableDel(index) {
      console.log('index', index)
      this.huikuandanTable.splice(index, 1)
      this.checkHuikuandanAll()
    },
    //校验回款单中的回款总额是否超出合同总价
    //如果超出 回款单按钮不可用 更新可添加金额数值
    checkHuikuandanAll() {
      let huikuandanSum = null
      let yingshoukuanSum = null
      if (this.huikuandanTable.length <= 0 && this.yingshoukuanTable.length <= 0) {
        this.canBeAdd = this.model.contractAmount - 0
        this.huikuandanTableShow = false
        this.yingshoukuanTableShow = false
      } else {
        huikuandanSum = this.huikuandanTable.reduce((Sum, e) => {
          return Sum += Number(e.collectionAmount)
        }, 0)
        yingshoukuanSum = this.yingshoukuanTable.reduce((Sum, e) => {
          return Sum += Number(e.amountReceivable)
        }, 0)
        this.canBeAdd = this.model.contractAmount - huikuandanSum - yingshoukuanSum
      }
      this.canBeAdd > 0 ? this.huikuandanShow = false : this.huikuandanShow = true

    },
    //批量应收款按钮
    /* piliangYingshoukuan() {

    }, */
    //应收款按钮
    openYingshoukuan() {
      this.$refs.yingshoukuanModel.add()
      this.$refs.yingshoukuanModel.passON(this.canBeAdd)
    },
    //应收款回执
    yingshoukuanOK(res) {
      console.log('add应收款返回数据', res)
      const { yingshoukuanCount, yingshoukuanTable } = this
      if (res.key) {
        //编辑的情况
        const yingshoukuanTable = [...this.yingshoukuanTable]
        let target = yingshoukuanTable.find((item) => item.key == res.key)
        target = Object.assign(target, res)
        this.yingshoukuanTable = yingshoukuanTable
      } else {
        //新增的情况
        let newData = Object.assign(res, { key: yingshoukuanCount })
        this.yingshoukuanTable = [...this.yingshoukuanTable, newData]
        this.yingshoukuanCount += 1
      }

      //这里要区分是编辑还是新增的回传
      this.yingshoukuanTable.length > 0 ? this.yingshoukuanTableShow = true : this.yingshoukuanTableShow = false
      this.checkHuikuandanAll()
      console.log('回款单表格实时动态', this.yingshoukuanTable)
    },
    //应收款表格编辑
    yingshoukuanTableEdit(record) {
      console.log('record', record)
      this.$refs.yingshoukuanModel.edit(record)
      this.$refs.yingshoukuanModel.passONEdit(this.canBeAdd + Number(record.amountReceivable))
    },
    //应收款表格删除
    yingshoukuanTableDel(index) {
      console.log('index', index)
      this.yingshoukuanTable.splice(index, 1)
      this.checkHuikuandanAll()
    }
  }
}
</script>
<style scoped lang="less">
.cu-font {
  font-weight: bold;
}
</style>